using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SpoonCore2.Client;
using SpoonCore2.Message;
using SpoonCore2.OverlayNetwork.Pastry.Messages;
using SpoonCore2.Service;

namespace SpoonCore2.OverlayNetwork.Pastry.Messages
{
	class ExchangeMessage : AbstractMessage
	{
		public enum ExchangeType : byte
		{
			Request,
			Response
		}

		private ExchangeType _type = ExchangeType.Request;
		private readonly List<SearchMask> _searchList = new List<SearchMask>();
		private readonly List<ClientInfo> _clientInfo = new List<ClientInfo>();
		private bool _leaveSet = false;

		public ExchangeType Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public List<SearchMask> SearchList
		{
			get { return _searchList; }
		}

		public bool LeaveSet
		{
			get { return _leaveSet; }
			set { _leaveSet = value; }
		}

		public List<ClientInfo> Clients
		{
			get { return _clientInfo; }
		}

		public override void GetBytes(BinaryWriter bw)
		{
			bw.Write((byte)Type);
			bw.Write(_leaveSet);
			bw.Write(_searchList.Count);
			foreach (SearchMask mask in _searchList)
			{
				bw.Write(mask.GetBytes());
			}
			bw.Write(Clients.Count);
			foreach(ClientInfo client in Clients)
			{
				client.GetBytes(bw);
			}
		}

		public override void SetBytes(IService service, BinaryReader br)
		{
			Type = (ExchangeType) br.ReadByte();
			if(Type == ExchangeType.Response){}
			LeaveSet = br.ReadBoolean();
			int count = br.ReadInt32();
			while(count > 0)
			{
				SearchList.Add(new SearchMask(br));
				count--;
			}
			count = br.ReadInt32();
			while(count > 0)
			{
				Clients.Add(new ClientInfo(service, br));
				count--;
			}
		}
	}
}